package com.xhej.rowreat.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.MapComparator;
import com.xhej.rowreat.mapper.RowSeatMapper;
import com.xhej.rowreat.model.Bank;
import com.xhej.rowreat.model.Dimension;
import com.xhej.rowreat.model.ImportJson;
import com.xhej.rowreat.model.OutputJson;
import com.xhej.rowreat.model.Seat;
import com.xhej.rowreat.model.User;
import com.xhej.rowreat.service.RowSeatService;
import com.xhej.rowreat.util.ComparatorResultType;
import com.xhej.rowreat.util.Utils;
@Service
public class RowSeatServiceImpl implements RowSeatService {

	static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
	
	@Autowired
	private RowSeatMapper rowSeatMapper;
	
	//座位排序
	public List<Seat> orderSeat(ImportJson importJson){
		List<Seat> resList = new ArrayList<Seat>();
		List<Seat> list = importJson.getList();
		int frontCols = 0; //当前排数之前的所有排座位总和
		int manualNum = 0; //手工排座个数
		//对座位按行数大小升序排序
		ComparatorResultType comparator=new ComparatorResultType();
		Collections.sort(list, comparator); 
		System.out.print("-----------------order	seat	end     display--------------\n");
		//对座位排序
		for(Seat seat: list) {
			for(int i=1; i<=seat.getColumns(); i++) {
				Seat seatTmp = new Seat();
				//行数
				seatTmp.setRow(seat.getRow());
				//计算出第几列
				int n;
				if(seat.getColumns()%2 == 0) { //偶数：col/2+[(-1)^n×1/2×n+(3/4+1/4×(-1)^n)×(n%2)]
					n = (int) (seat.getColumns()/2+Math.pow(-1, i)*1/2*i+((double)3/4+1/4*Math.pow(-1, i))*(i%2));
				}else { //奇数：col/2+[(-1)^(n+1)×1/2×n-(3/4+1/4×(-1)^(n+1))×(n%2)]+1
					n = (int) (seat.getColumns()/2+Math.pow(-1, i+1)*1/2*i-(3/4+1/4*Math.pow(-1,i+1))*(i%2)+1);
				}
				seatTmp.setColumn(n);
				//座位编号
				seatTmp.setSeatId(Integer.toString(frontCols+n));
				//是否手工排座
				if(!Utils.isNullOrEmpty(importJson.getManualSeatList()) && importJson.getManualSeatList().size() > 0) {
					for(Seat mSeat: importJson.getManualSeatList()) {
						if(seatTmp.getRow()==mSeat.getRow() && seatTmp.getColumn()==mSeat.getColumn()) {
							seatTmp.setOrder(true);
							manualNum++;
							break;
						}
					}
				}
				//不是手工排座，添加自动排座序号
				if(!seatTmp.isOrder()) {
					seatTmp.setOrderNum(Integer.toString(frontCols+i-manualNum)); //排座序号
				}else {
					seatTmp.setOrderNum("");
				}
				System.out.print("Row: "+seatTmp.getRow()+", Col："+seatTmp.getColumn()+"，OrderNum："+seatTmp.getOrderNum()+"，IsOrder："+seatTmp.isOrder()+"，seatId："+seatTmp.getSeatId()+"|");
				resList.add(seatTmp);
			}
			frontCols += seat.getColumns();
			System.out.print("\n");
		}
		return resList;
	}
	
	
	//人排序
	@SuppressWarnings("unchecked")
	public List<User> orderUser(List<User> list,List<Dimension> dimensionList,List<Bank> banklist){
		// 将人的list转换为map
		Map<String,Map<String,Object>> listMapUser = new HashMap<String,Map<String,Object>>();
		for(User user : list){
			Map<String,Object> map = new HashMap<String,Object>(); 
			Map<String,Object> map2 = new HashMap<String,Object>(); 
			List<Double> userDimList = new ArrayList<>();
			map2 = Utils.bean2map(user,User.class);
			map.put(user.getId(), map2);
			// 存放每次产生的维度值
			map.put("userDimList", userDimList);
			listMapUser.put(user.getId(),map);
		}
		// 将机构的list转换为map
		Map<String,Map<String,Object>> listMapBank = new HashMap<String,Map<String,Object>>();
		for(Bank bank : banklist){
			Map<String,Object> map = new HashMap<String,Object>(); 
			Map<String,Object> map2 = new HashMap<String,Object>(); 
			List<Double> bankDimList = new ArrayList<>();
			map2 = Utils.bean2map(bank,Bank.class);
			map.put(bank.getBankId(), map2);
			// 存放每次产生的维度值
			map.put("bankDimList", bankDimList);
			listMapBank.put(bank.getBankId(),map);
		}
		// 获取当前维度以及计算公式
		String dimension = null;
		// 获取当前维度计算公式
		String formula = null;
		// 获取当前唯独计算公式
		String obj = "user";
		// 获取当前需要计算权重的维度以及公式
		for(Dimension entity:dimensionList) {
			dimension = entity.getDimension();
			formula = entity.getFormula();
			obj = entity.getObj();
			if(dimension.isEmpty()||formula.isEmpty()) {
				continue;
			}
			// 定位维度值
			double dimensionVal = 0;
			// 定义当前维度权重
			Object weightVal = 0;	
			// 判断当前维度针对个人还是针对机构
			// 针对个人
			if(obj.equals("user")) {
				// 循环当前所有人的对象，计算当前的维度的权重值
				for(User user : list) {
					// 获取当前人对应的map
					HashMap<String, Object> map = (HashMap<String, Object>) listMapUser.get(user.getId());
					HashMap<String, Object> map2user = (HashMap<String, Object>) map.get(user.getId());
					List<Double> userDimList = (List<Double>) map.get("userDimList");
					// 获取当前让人对应的维度值
					dimensionVal = Double.parseDouble(map2user.get(dimension).toString());
					
					weightVal = Utils.functionCalculation(formula,dimensionVal);
					userDimList.add(Double.parseDouble(weightVal.toString()));
					// 替换原有的维度值list
					map.remove("userDimList");
					map.put("userDimList", userDimList);
					// 替换原有的map
					listMapUser.remove(user.getId());
					listMapUser.put(user.getId(), map);
				}
				// 针对机构
			} else {
				// 循环当前所有人的对象，计算当前的维度的权重值
				for(Bank bank : banklist) {
					// 获取当前人对应的map
					HashMap<String, Object> map = (HashMap<String, Object>) listMapBank.get(bank.getBankId());
					HashMap<String, Object> map2bank = (HashMap<String, Object>) map.get(bank.getBankId());
					List<Double> bankDimList = (List<Double>) map.get("bankDimList");
					// 获取当前让人对应的维度值
					dimensionVal = Double.parseDouble(map2bank.get(dimension).toString());
					weightVal = Utils.functionCalculation(formula,dimensionVal);
					bankDimList.add(Double.parseDouble(weightVal.toString()));
					// 替换原有的维度值list
					map.remove("userDimList");
					map.put("userDimList", bankDimList);
					// 替换原有的map
					listMapUser.remove(bank.getBankId());
					listMapUser.put(bank.getBankId(), map);
				}
			}
		}
		List<User> listuser = new ArrayList<>();
		// 计算当前人的权重
		for(User user : list) {
			// 获取个人所有权重
			// 获取当前人对应的map
			HashMap<String, Object> mapuser = (HashMap<String, Object>) listMapUser.get(user.getId());
			// 获取当前人对应的维度权重集
			List<Double> userDimList = (List<Double>) mapuser.get("userDimList");
			// 定义当前人权重
			double translate = 0;
			// 获取个人所有权重
			for(int i=0; i<userDimList.size();i++) {
				translate += userDimList.get(i);
			}
			// 获取当前人所在机构
			String bankId = user.getBankId();
			// 获取机构对应的map
			HashMap<String, Object> mapbank = (HashMap<String, Object>) listMapBank.get(bankId);
			// 获取机构对应的维度权重集
			List<Double> bankDimList = (List<Double>) mapbank.get("bankDimList");
			// 获取机构权重
			for(int i=0; i<bankDimList.size();i++) {
				translate += bankDimList.get(i);
			}
			user.setTranslate(String.valueOf(translate));
			listuser.add(user);
		}
		List<Map<String, Object>> sortUserList = new ArrayList<Map<String, Object>>();
		for(User u : listuser) {
			sortUserList.add(Utils.bean2map(u, User.class));
		}
		// 结果按 权重排序
		Collections.sort(sortUserList, new MapComparator("translate", true));
		listuser.removeAll(listuser);
		int i = 0;
		for(Map<String, Object> m : sortUserList) {
			try {
				i++;
				// 将map转换未bean
				User user = Utils.map2bean(m, User.class);
				user.setSequence(String.valueOf(i));
				listuser.add(user);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return listuser;
	}
	
	
	//人排序
	@SuppressWarnings("unchecked")
	public List<User> orderUser2(List<Map<String,Object>> list,List<Map<String,Object>> dimensionList,List<Map<String,Object>> banklist){
		// 将人的list转换为map
		List<Map<String,Object>> listMapUser = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> listMapUser1 = new ArrayList<Map<String,Object>>();
		// 获取不参与排序的人的集合
		List <String> nouserList =Utils.readExcelOne("nouser.xls");
		for(Map<String,Object> user : list){
			// 获取不参与排序的人的集合
			if(nouserList.contains(user.get("id"))) {
				continue;
			}
			nouserList.contains(user.get("id"));
			// 定义list用于存放每次产生的本人的维度值
			List<Double> userDimList = new ArrayList<>();
			// 存放每次产生的维度值
			user.put("userDimList", userDimList);
			listMapUser.add(user);
		}
		if(listMapUser==null ||listMapUser.size()==0) {
			return null;
			
		}
		// 将机构的list转换为map
		List<Map<String,Object>> listMapBank = new ArrayList<Map<String,Object>>();
		
		Map<String,Map<String,Object>> listMapBank1 = new HashMap<String,Map<String,Object>>();
		for(Map<String,Object> bank : banklist){
			// 定义list用于存放每次产生的本人的维度值
			List<Double> bankDimList = new ArrayList<>();
			// 存放每次产生的维度值
			bank.put("bankDimList", bankDimList);
			listMapBank1.put(String.valueOf(bank.get("bankId")), bank);
			listMapBank.add(bank);
		}
		// 获取当前维度以及计算公式
		String dimension = null;
		// 获取当前维度计算公式
		String formula = null;
		// 获取当前唯独计算公式
		String obj = "user";
		// 获取当前需要计算权重的维度以及公式
		for(Map<String,Object> entity:dimensionList) {
			dimension = String.valueOf(entity.get("dimension"));
			formula = String.valueOf(entity.get("formula"));
			obj = String.valueOf(entity.get("obj"));
			if(dimension.isEmpty()||formula.isEmpty()) {
				continue;
			}
			// 定位维度值
			double dimensionVal = 0;
			// 定义当前维度权重
			Object weightVal = 0;	
			// 判断当前维度针对个人还是针对机构
			// 针对个人
			if(obj.equals("user")) {
				// 循环当前所有人的对象，计算当前的维度的权重值
				for(Map<String,Object> user : listMapUser) {
					// 获取当前人对应的各维度存储维度值list
					List<Double> userDimList = (List<Double>) user.get("userDimList");
					// 获取当前人对应的维度值
					dimensionVal = Double.parseDouble(user.get(dimension).toString());
					// 获取当前维度权重值
					weightVal = Utils.functionCalculation(formula,dimensionVal);
					userDimList.add(Double.parseDouble(weightVal.toString()));
					// 替换原有的维度值list
					user.remove("userDimList");
					user.put("userDimList", userDimList);
					listMapUser1.add(user);
				}
				// 针对机构
			} else {
				// 循环当前所有人的对象，计算当前的维度的权重值
				for(Map<String,Object> bank : listMapBank) {
					listMapBank1.remove(bank.get("bankId"));
					// 获取当前机构对应的各维度存储维度值list
					List<Double> bankDimList = (List<Double>) bank.get("bankDimList");
					// 获取当前机构对应的维度值
					dimensionVal = Double.parseDouble(bank.get(dimension).toString());
					// 获取当前维度权重值
					weightVal = Utils.functionCalculation(formula,dimensionVal);
					bankDimList.add(Double.parseDouble(weightVal.toString()));
					// 替换原有的维度值list
					bank.remove("bankDimList");
					bank.put("bankDimList", bankDimList);
					// 替换原有的map
					listMapBank1.put(String.valueOf(bank.get("bankId")), bank);
				}
			}
		}
		List<User> listuser = new ArrayList<>();
		List<Map<String, Object>> sortUserList = new ArrayList<Map<String, Object>>();
		// 计算当前人的权重
		for(Map<String,Object> userQz : listMapUser) {
			// 获取当前人对应的维度权重集
			List<Double> userDimList = (List<Double>) userQz.get("userDimList");
			// 定义当前人权重
			double translate = 0;
			// 获取个人所有权重
			for(int i=0; i<userDimList.size();i++) {
				translate += userDimList.get(i);
			}
			// 取得机构权重集
			HashMap<String, Object> mapbank = (HashMap<String, Object>) listMapBank1.get(userQz.get("bankId"));
			// 获取机构对应的维度权重集
			List<Double> bankDimList = (List<Double>) mapbank.get("bankDimList");
			// 获取机构权重
			for(int i=0; i<bankDimList.size();i++) {
				translate += bankDimList.get(i);
			}
			userQz.put("translate", String.valueOf(translate));
			
			sortUserList.add(userQz);
		}
		// 排序
		Utils.sortListBySingleMapKey(sortUserList, "translate", false);
		// 封装数据
		int i = 0;
		for(Map<String, Object> m : sortUserList) {
			try {
				i++;
				// 将map转换未bean
				User user = Utils.map2bean(m, User.class);
				user.setSequence(String.valueOf(i));
				listuser.add(user);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return listuser;
	}
	
	
	//优化
	public OutputJson optResult(List<Seat> listSeat, List<User> listUser, ImportJson importJson){
		OutputJson outputJson = new OutputJson();
		//规则
		outputJson.setRule(importJson.getRule());
		//结果list
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for(Seat s : listSeat) {
			if(!s.isOrder()) {
				Map<String, Object> m = new HashMap<String, Object>();
				m.put("row", s.getRow());
				m.put("column", s.getColumn());
				m.put("seatNo", s.getSeatId());
				m.put("orderNum", s.getOrderNum());
				for(User u : listUser) {
					if(s.getOrderNum().equals(String.valueOf(u.getSequence()))) {
						m.put("name", u.getUsername());
						m.put("title", u.getPosition());
						m.put("bankId", u.getBankId());
						break;
					}
				}
				
				//未安排人的座位返回姓名，职衔，机构号为空
				if(m.get("name")==null && m.get("title")==null && m.get("bankId")==null){
					m.put("name", "");
					m.put("title", "");
					m.put("bankId", "");
				}
				list.add(m);
			}
		}
		//先默认排座的位置和人的数目相同，可优化
		for(int i = 0; i < list.size(); i++) {
//			list.get(i).put("name", listUser.get(i).getUsername());
//			list.get(i).put("title", listUser.get(i).getPosition());
			for(int j = 0; j < importJson.getBanklist().size(); j++) {
				if(importJson.getBanklist().get(j).getBankId().equals(list.get(i).get("bankId"))) {
					list.get(i).put("org", importJson.getBanklist().get(j).getBankName());
					break;
				}
			}
			//未安排人的座位返回机构名称为空
			if(list.get(i).get("org")==null) {
				list.get(i).put("org", "");
			}
		}

		//优化：职位第低于2.2的往一起排
//		for(Map<String, Object> m : list) {
//			if(!Utils.isNullOrEmpty(m.get("name"))) {
//				System.out.println("1");
//			}
//		}
		
		//配对后排序
		outputJson.setList(list);
			
		//优化：
		return outputJson;
	}
		
	
	

}
